/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package trituenhantao;

import Objects.Map;
import Objects.Square;
import algoristhm.Astar2;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.Timer;
import javax.swing.border.TitledBorder;

/**
 *
 * @author William
 */
public class Main extends JFrame implements MouseListener, ActionListener {

    boolean isRunning = false;
    Timer timer = new Timer(500, this);

    @Override
    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == btnSave){
            JFileChooser saver= new JFileChooser();
            if (saver.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                MainHandle.Save(cell, saver.getSelectedFile().getPath());
               
            }
//           
        }
        
        if (ae.getSource() == btnOpen){
            JFileChooser open= new JFileChooser();
            if (open.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                 cell=MainHandle.Open(open.getSelectedFile().getPath());
            }
            for (int j = 0; j < height; j++) {
                for (int i = 0; i < width; i++) {
                    cell[i][j].setStatus(cell[i][j].getStatus());
                    truckQuantity = 0;
                    siteQuantity = 0;
                }
            }
        }
        
        if (ae.getSource() == btnReset) {
            timer.stop();
            isRunning=false;
            for (int j = 0; j < height; j++) {
                for (int i = 0; i < width; i++) {
                    cell[i][j].setStatus(0);
                    cell[i][j].setPreviousStt(0);
                    truckQuantity = 0;
                    siteQuantity = 0;
                }
            }
        }

        if (ae.getSource() == btnStart) {
            isRunning = true;
            if (timer.isRunning()) {
                timer.stop();
            }
            if (truckQuantity == 0) {
                JOptionPane.showMessageDialog(this, "Chưa đặt vị trí xe tải");
            } else if (siteQuantity == 0) {
                JOptionPane.showMessageDialog(this, "Chưa đặt vị trí công trường");
            } else {
                Astar2 a = new Astar2(cell, start, finish);

                ArrayList<Square> path = a.findPath();
                if (path != null) {
                    for (int i = 0; i < path.size(); i++) {
                        if (path.get(i).getStatus() != 1) {
                            path.get(i).setPreviousStt(path.get(i).getStatus());
                        }else{
                            path.get(i).setPreviousStt(0);
                        }
                    }

                    timer = new Timer(500, new ActionListener() {
                        int count = path.size();

                        @Override
                        public void actionPerformed(ActionEvent ae) {
                            count--;
                            start.setStatus(0);
                            if (count > 0) {
                                
                                if (count + 1 < path.size()) {
                                    path.get(count + 1).setStatus(path.get(count + 1).getPreviousStt());
                                }
                                path.get(count).setStatus(1);
                                start = path.get(count);
                                if (count == 0) {
                                    isRunning = false;
                                    timer.stop();
                                    
                                }
                            }
                        }

                    }
                    );
                    timer.start();

                    
                } else {
                    JOptionPane.showMessageDialog(this, "Không tìm được đường :'(");
                }
            }

        }
    }

    //chieu rong va chieu cao cua map
    private static int width = 20;
    private static int height = 20;
    private static int stt = 0;
    private static int truckQuantity = 0;
    private static Square start = new Square("", -1, -1);
    private static int siteQuantity = 0;
    private static Square finish = new Square("", -1, -1);
    //create map
    JPanel pnlMap;
    Square[][] cell;

    private void createMap(int x, int y) {
        pnlMap = new JPanel();
        pnlMap.setLayout(new GridLayout(width, height));
        pnlMap.setBorder(BorderFactory.createTitledBorder("Bản đồ"));
        pnlMap.setPreferredSize(new Dimension(600, 600));
        cell = new Square[width][height];
        for (int j = 0; j < height; j++) {
            for (int i = 0; i < width; i++) {
                cell[i][j] = new Square("", i, j);
                pnlMap.add(cell[i][j]);

                cell[i][j].addMouseListener(this);

            }
        }
        getContentPane().add(pnlMap, BorderLayout.CENTER);
    }
    //create info panel
    JPanel pnlInfo;
    ImageIcon iconWall = new ImageIcon("image/wall.png");
    ImageIcon iconWallS = new ImageIcon("image/wallSelect.png");
    ImageIcon iconWater = new ImageIcon("image/water.png");
    ImageIcon iconWaterS = new ImageIcon("image/waterSelect.png");
    ImageIcon iconTrees = new ImageIcon("image/trees.png");
    ImageIcon iconTreesS = new ImageIcon("image/treesSelect.png");
    ImageIcon iconTruck = new ImageIcon("image/truck.png");
    ImageIcon iconTruckS = new ImageIcon("image/truckSelect.png");
    ImageIcon iconEarth = new ImageIcon("image/earth.png");
    ImageIcon iconEarthS = new ImageIcon("image/earthSelect.png");
    ImageIcon iconSite = new ImageIcon("image/site.jpg");
    ImageIcon iconSiteS = new ImageIcon("image/siteSelect.png");

    ButtonGroup grpRdo = new ButtonGroup();
    JRadioButton rdoWall = new JRadioButton(iconWall);
    JRadioButton rdoWater = new JRadioButton(iconWater);
    JRadioButton rdoTrees = new JRadioButton(iconTrees);
    JRadioButton rdoTruck = new JRadioButton(iconTruck);
    JRadioButton rdoEarth = new JRadioButton(iconEarth);
    JRadioButton rdoSite = new JRadioButton(iconSite);

    JButton btnStart = new JButton("Bắt đầu");
    JButton btnReset = new JButton("Xóa bản đồ");
    JButton btnSave = new JButton("Lưu bản đồ");
    JButton btnOpen = new JButton("Mở bản đồ");

    private void createInfo() {
        rdoWall.setText("Tường");
        rdoWater.setText("Vũng nước");
        rdoTrees.setText("Bụi cây");
        rdoTruck.setText("Xe tải");
        rdoEarth.setText("Nền đất");
        rdoSite.setText("Công trường");

        rdoWall.setSelectedIcon(iconWallS);
        rdoWater.setSelectedIcon(iconWaterS);
        rdoTrees.setSelectedIcon(iconTreesS);
        rdoTruck.setSelectedIcon(iconTruckS);
        rdoEarth.setSelectedIcon(iconEarthS);
        rdoSite.setSelectedIcon(iconSiteS);

        grpRdo.add(rdoWall);
        grpRdo.add(rdoWater);
        grpRdo.add(rdoTrees);
        grpRdo.add(rdoTruck);
        grpRdo.add(rdoEarth);
        grpRdo.add(rdoSite);

        pnlInfo = new JPanel();
        pnlInfo.setLayout(null);
        pnlInfo.setBorder(new TitledBorder("Thông tin"));
        pnlInfo.setPreferredSize(new Dimension(200, 600));

        rdoTruck.setBounds(30, 50, 150, 30);
        rdoSite.setBounds(30, 90, 150, 30);
        rdoWall.setBounds(30, 130, 150, 30);
        rdoWater.setBounds(30, 170, 150, 30);
        rdoTrees.setBounds(30, 210, 150, 30);
        rdoEarth.setBounds(30, 250, 150, 30);
        btnStart.setBounds(30, 290, 150, 30);
        btnStart.addActionListener(this);
        btnReset.setBounds(30, 330, 150, 30);
        btnReset.addActionListener(this);
        btnSave.setBounds(30,370,150,30);
        btnSave.addActionListener(this);
        btnOpen.setBounds(30,410,150,30);
        btnOpen.addActionListener(this);

        pnlInfo.add(rdoTruck);
        pnlInfo.add(rdoWall);
        pnlInfo.add(rdoWater);
        pnlInfo.add(rdoTrees);
        pnlInfo.add(rdoEarth);
        pnlInfo.add(rdoSite);
        pnlInfo.add(btnStart);
        pnlInfo.add(btnReset);
        pnlInfo.add(btnSave);
        pnlInfo.add(btnOpen);
        getContentPane().add(pnlInfo, BorderLayout.EAST);
    }

    public Main() throws HeadlessException {
//        //nimbus look and feel
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
        setVisible(true);
        setTitle("Robot tim duong");
        setSize(800, 600);
        setLayout(new BorderLayout());

        createMap(width, height);
        createInfo();
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new Main();
    }
    private int mouseStatus = -1;

    @Override
    public void mouseClicked(MouseEvent me) {

    }

    @Override
    public void mousePressed(MouseEvent me) {
        timer.stop();
        for (int x = 0; x < height; x++) {
            for (int y = 0; y < width; y++) {
                if (me.getSource() == cell[x][y]) {
                    if (rdoTruck.isSelected() == true && truckQuantity == 0) {

                        stt = 1;
                        cell[x][y].setStatus(1);
                        start.setXx(x);
                        start.setYy(y);
                        start.setPreviousStt(0);
                        truckQuantity = 1;

                    }
                    if (rdoSite.isSelected() == true && siteQuantity == 0) {

                        stt = 100;
                        cell[x][y].setStatus(100);
                        siteQuantity = 1;
                        finish.setXx(x);
                        finish.setYy(y);

                    }

                    if (rdoWall.isSelected() == true) {
                        stt = 10;
                    } else if (rdoTrees.isSelected() == true) {
                        stt = 5;
                    } else if (rdoWater.isSelected() == true) {
                        stt = 2;
                    } else if (rdoEarth.isSelected() == true) {
                        stt = 0;
                    }

                    if (stt != 1 && stt != 100) {
                        cell[x][y].setStatus(stt);
                        if (x == start.getXx() && y == start.getYy()) {
                            truckQuantity = 0;

                            start.setXx(-1);
                            start.setYy(-1);
                        }
                        if (x == finish.getXx() && y == finish.getYy()) {
                            siteQuantity = 0;

                            finish.setXx(-1);
                            finish.setYy(-1);
                        }
                    }
                }
            }
        }
        mouseStatus = stt;
    }
    
    @Override
    public void mouseReleased(MouseEvent me) {
        mouseStatus = -1;
        if (isRunning == true) {

            Astar2 a = new Astar2(cell, start, finish);

            ArrayList<Square> path = a.findPath();
            if (path != null) {
                for (int i = 0; i < path.size(); i++) {
                    if (path.get(i).getStatus() != 1) {
                        path.get(i).setPreviousStt(path.get(i).getStatus());
                    }
                }

                timer = new Timer(500, new ActionListener() {
                    int count = path.size();

                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        count--;
                        start.setStatus(0);
                        if (count > 0) {
                            if (count == path.size() - 1) {
                                path.get(count).setStatus(0);
                            }
                            if (count + 1 < path.size() - 1) {
                                path.get(count + 1).setStatus(path.get(count + 1).getPreviousStt());
                            }
                            path.get(count).setStatus(1);
                            start = path.get(count);
                            if (count == 0) {
                                isRunning = false;
                                timer.stop();
                            }
                        }
                    }

                }
                );
                timer.start();
            }else{
                JOptionPane.showMessageDialog(this, "Hết đường đi rồi");
                
            }

        }
    }

    @Override
    public void mouseEntered(MouseEvent me) {
        if (mouseStatus != -1) {
            for (int x = 0; x < height; x++) {
                for (int y = 0; y < width; y++) {
                    if (me.getSource() == cell[x][y] && stt != 1 && stt != 100) {
                        cell[x][y].setStatus(stt);
                        if (x == start.getXx() && y == start.getYy()) {
                            truckQuantity = 0;

                            start.setXx(-1);
                            start.setYy(-1);
                        }
                        if (x == finish.getXx() && y == finish.getYy()) {
                            siteQuantity = 0;

                            finish.setXx(-1);
                            finish.setYy(-1);
                        }
                    }
                }
            }
        }
    }

    @Override
    public void mouseExited(MouseEvent me) {

    }
}
